<template>
  <a-modal 
    v-model:visible="visible"
    title="Update User Information"
    :width="1000"
    :footer="false"
    @cancel="handleCancel"
    :mask-closable="false"
  >
    <div class="flex items-start pt-2 pb-4">
      <!-- 头像上传 -->
      <div class="w-[103px] mx-8 flex items-center justify-center overflow-hidden self-start">
        <a-upload
          action="/"
          :fileList="avatar ? [avatar] : []"
          :show-file-list="false"
          @change="onChange"
          @progress="onProgress"
        >
          <template #upload-button>
            <div
              :class="`arco-upload-list-item${
                avatar && avatar.status === 'error' ? ' arco-upload-list-item-error' : ''
              }`"
            >
              <div
                class="arco-upload-list-picture custom-upload-avatar !w-[100px] !h-[100px] !rounded-full !m-0"
                v-if="avatar && avatar.url"
              >
                <img :src="avatar.url" />
                <div class="arco-upload-list-picture-mask">
                  <IconEdit />
                </div>
                <a-progress
                  v-if="avatar.status === 'uploading' && avatar.percent < 100"
                  :percent="avatar.percent"
                  type="circle"
                  size="mini"
                  :style="{
                    position: 'absolute',
                    left: '50%',
                    top: '50%',
                    transform: 'translateX(-50%) translateY(-50%)',
                  }"
                />
              </div>
              <div v-else class="flex flex-col items-center justify-center h-full">
                <img src="@/assets/images/login-avatar.png" alt="Avatar" class="w-full h-full object-cover" />
                <a-button type="primary" class="mt-2">Upload</a-button>
              </div>
            </div>
          </template>
        </a-upload>
      </div>

      <!-- 表单容器 -->
      <div class="flex-grow">
        <a-form
          :model="userForm"
          :rules="userRules"
          @submit="handleUpdate"
          layout="vertical"
          class="w-full"
        >
          <a-divider orientation="left">
            <div class="font-bold">Contact Information</div>
          </a-divider>
          <a-row :gutter="24">
            <a-col :span="12">
              <a-form-item field="profile.nickName" label="Nickname" class="mb-4" required>
                <a-input
                  v-model="userForm.profile.nickName"
                  size="large"
                />
                <a-button 
                  @click="generateNickname"
                  size="large"
                  type="outline"
                  class="ml-2"
                >
                  random
                </a-button>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <!-- 空列用于布局平衡 -->
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="12">
              <a-form-item field="profile.firstName" label="First Name" class="mb-4">
                <a-input
                  v-model="userForm.profile.firstName"
                  placeholder="First Name"
                  size="large"
                  class="w-full"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="profile.lastName" label="Last Name" class="mb-4">
                <a-input
                  v-model="userForm.profile.lastName"
                  placeholder="Last Name"
                  size="large"
                  class="w-full"
                />
              </a-form-item>
            </a-col>
          </a-row>
          <a-form-item field="profile.gender" label="Gender" class="mb-4">
            <a-radio-group v-model="userForm.profile.gender">
              <a-radio value="male">
                <template #radio="{ checked }">
                  <icon-man 
                    style="stroke-width: 5" 
                    :class="`!w-[25px] !h-[25px] !p-[4px] bg-primary rounded-full !text-white mr-2 ${checked ? 'opacity-100' : 'opacity-50'}`"
                  />Male
                </template>
              </a-radio>
              <a-radio value="female">
                <template #radio="{ checked }">
                  <icon-woman 
                    style="stroke-width: 5" 
                    :class="`!w-[25px] !h-[25px] !p-[4px] bg-primary rounded-full !text-white mr-2 ${checked ? 'opacity-100' : 'opacity-50'}`"
                  />Female
                </template>
              </a-radio>
              <a-radio value="secret">
                <template #radio="{ checked }">
                  <icon-lock 
                    style="stroke-width: 5" 
                    :class="`!w-[25px] !h-[25px] !p-[4px] bg-primary rounded-full !text-white mr-2 ${checked ? 'opacity-100' : 'opacity-50'}`"
                  />Secret
                </template>
              </a-radio>
            </a-radio-group>
          </a-form-item>
          <a-row :gutter="24">
            <a-col :span="12">
              <a-form-item field="profile.location.country" label="Country" class="mb-4">
                <a-select
                  v-model="userForm.profile.location.country"
                  placeholder="Select a country"
                  size="large"
                  class="w-full"
                >
                  <a-option value="us">United States</a-option>
                  <a-option value="ca">Canada</a-option>
                  <a-option value="gb">United Kingdom</a-option>
                  <a-option value="au">Australia</a-option>
                  <a-option value="other">Other</a-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="profile.location.city" label="City" class="mb-4">
                <a-input
                  v-model="userForm.profile.location.city"
                  placeholder="City"
                  size="large"
                  class="w-full"
                />
              </a-form-item>
            </a-col>
          </a-row>
          <a-divider orientation="left">
            <div class="font-bold">Professional Information</div>
          </a-divider>
          <a-row :gutter="24">
            <a-col :span="12">
              <a-form-item field="profile.affiliation.type" label="Institution Type" class="mb-4">
                <a-select
                  v-model="userForm.affiliation.type"
                  placeholder="Select a institution type"
                  size="large"
                  class="w-full"
                >
                  <a-option value="hospital">Hospital</a-option>
                  <a-option value="school">School</a-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="profile.affiliation.name" label="Institution Name" class="mb-4">
                <a-input
                  v-model="userForm.affiliation.name"
                  placeholder="Institution Name"
                  size="large"
                  class="w-full"
                />
              </a-form-item>
            </a-col>
          </a-row>
          
          <!-- 更新按钮 -->
          <a-button
            type="primary"
            html-type="submit"
            :loading="loading"
            long
            size="large"
            class="bg-primary hover:bg-primary-dark transition-all duration-300 shadow-md hover:shadow-lg rounded-lg"
          >
            Update
          </a-button>
        </a-form>
      </div>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { reactive, ref, computed, watch } from 'vue'
import { Message } from '@arco-design/web-vue'
import { useUserStore } from '@/stores/user'
import { generateRandomNickname } from '@/utils/tool'
import { updateUserInfoApi } from '@/api/user'

interface Props {
  visible: boolean
  userInfo?: any
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'success'): void
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  userInfo: () => ({})
})
const emit = defineEmits<Emits>()
const userStore = useUserStore()

const visible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

const loading = ref(false)

// 监听用户信息变化，初始化表单
watch(() => props.userInfo, (newUserInfo) => {
  if (newUserInfo && Object.keys(newUserInfo).length > 0) {
    initFormData()
  }
}, { immediate: true })

// 用户信息表单
const userForm = reactive({
  profile: {
    nickName: '',
    firstName: '',
    lastName: '',
    gender: '',
    avatar: '',
    location: {
      country: '',
      city: ''
    }
  },
  affiliation: {
    type: '',
    name: '',
    expert_info: []
  }
})

const avatar = ref()

// 表单验证规则
const userRules = {
  'profile.nickName': [
    { required: true, message: 'Please enter your nickname.' }
  ],
  'profile.firstName': [
    { required: true, message: 'Please enter your first name.' }
  ],
  'profile.lastName': [
    { required: true, message: 'Please enter your last name.' }
  ],
  'profile.gender': [
    { required: true, message: 'Please select your gender.' }
  ],
  'profile.location.country': [
    { required: true, message: 'Please select your country.' }
  ],
  'profile.location.city': [
    { required: true, message: 'Please enter your city.' }
  ]
}

// 更新用户信息处理
const handleUpdate = async ({ values, errors }: any) => {
  if (errors) return
  
  loading.value = true
  try {
    // 调用更新用户信息 API
    const uid = props.userInfo?.uid || props.userInfo?.id || userStore.userInfo?.uid || userStore.userInfo?.id || localStorage.getItem('uid')
    if (!uid) {
      Message.error('User ID not found')
      return
    }
    
    const res = await updateUserInfoApi(uid, values)
    if (res.code === 0) {
      Message.success('User information updated successfully.')
      visible.value = false
      emit('success')
      // 更新本地用户信息
      if (userStore.userInfo) {
        Object.assign(userStore.userInfo, values)
      }
    } else {
      Message.error(res.msg || 'Update failed.')
    }
  } catch (error: any) {
    Message.error(error.response?.data?.msg || 'Update request failed.')
  } finally {
    loading.value = false
  }
}

// 取消处理
const handleCancel = () => {
  visible.value = false
  resetForm()
}

// 重置表单
const resetForm = () => {
  userForm.profile.nickName = ''
  userForm.profile.firstName = ''
  userForm.profile.lastName = ''
  userForm.profile.gender = ''
  userForm.profile.avatar = ''
  userForm.profile.location.country = ''
  userForm.profile.location.city = ''
  userForm.affiliation.type = ''
  userForm.affiliation.name = ''
}

// 生成随机昵称
const generateNickname = () => {
  userForm.profile.nickName = generateRandomNickname()
}

// 头像上传相关
const onChange = (_: any, currentFile: any) => {
  avatar.value = {
    ...currentFile,
    // url: URL.createObjectURL(currentFile.file),
  }
}

const onProgress = (currentFile: any) => {
  avatar.value = currentFile
}

// 初始化表单数据（从用户信息中加载）
const initFormData = () => {
  const sourceUserInfo = props.userInfo || userStore.userInfo
  if (sourceUserInfo && sourceUserInfo.profile) {
    const profile = sourceUserInfo.profile
    userForm.profile.nickName = profile.nickName || ''
    userForm.profile.firstName = profile.firstName || ''
    userForm.profile.lastName = profile.lastName || ''
    userForm.profile.gender = profile.gender || ''
    userForm.profile.avatar = profile.avatar || ''
    userForm.profile.location.country = profile.location?.country || ''
    userForm.profile.location.city = profile.location?.city || ''
    userForm.affiliation.type = profile.affiliation?.type || ''
    userForm.affiliation.name = profile.affiliation?.name || ''
  }
}

// 监听弹窗显示状态，初始化表单数据
watch(() => props.visible, (newVal) => {
  if (newVal) {
    initFormData()
  }
})
</script>

<style scoped>
</style>